#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/ip.h>
#include <netdb.h>
#include <dirent.h>
#include <fcntl.h>

int main(int argc, char *argv[])
{
	int svr_fd;
	int ret;
	unsigned short port;
	char buf[1024];
	struct sockaddr_in	name;
	struct hostent *tmp;
	socklen_t name_len;

	if(argc != 3){
		printf("Usage: URL[IP] Port\n");
		exit(1);
	}

	svr_fd = socket(AF_INET, SOCK_DGRAM, 0);
	if(svr_fd < 0){
		fprintf(stderr, "create_socket failed");
		exit(-1);
	}
	
	port = atoi(argv[2]);
	tmp = gethostbyname(argv[1]);

	memset(&name, 0, sizeof(name));
	name.sin_family = AF_INET;
	name.sin_addr = *(struct in_addr *)tmp->h_addr;
	name.sin_port = htons(port);

	while(1)
	{
		memset(buf, 0, sizeof(buf));
		fprintf(stderr, ">>");
		if(fgets(buf, sizeof(buf), stdin) == NULL){
			fprintf(stderr, "fgets failed");
			break;
		}

		ret = sendto(svr_fd, buf, sizeof(buf), 
					0, (struct sockaddr *)&name, sizeof(name));
		if(ret < 0){
			perror("sendto");
			exit(-1);
		}

		memset(buf, 0, sizeof(buf));
		usleep(500);

		ret = recvfrom(svr_fd, buf, sizeof(buf), 
				0, (struct sockaddr *)&name, &name_len);
		if(ret < 0){
			perror("recvfrom");
			exit(-1);
		}

		fprintf(stderr, "Server: %s\n", buf);
	}

	return 0;
}